<?php
        /*
        // File:        sslfunc.php
        // Purpose:     ssl functions
        // Creation:    2005-02-19
        // Author:      Mike
        */


// load libraries that we depend on
if (!class_exists('OpenSSL')) {
class OpenSSL{

    var $privatekey;    //resource or string private key
    var $publickey;        //ditto public
    var $plaintext;
    var $crypttext;
    var $ekey;            //ekey - set by encryption, required by decryption
    var $privkeypass;    //password for private key
    var $csr;            //certificate signing request string generated with keys
    var $config;
    
    function OpenSSL(){
    	global $cfg;
        $this->config = array("config" => $cfg['OPEN_SSL_CONF_PATH']);
    }
    
    function readf($path){
        //return file contents
        $fp=fopen($path,"r");
        $ret=fread($fp,8192);
        fclose($fp);
        return $ret;
    }
    
    //privatekey can be text or file path
    function set_privatekey($privatekey, $isFile=0, $key_password=""){
        
        if ($key_password) $this->privkeypass=$key_password;
        
        if ($isFile)$privatekey=$this->readf($privatekey);
        
        $this->privatekey=openssl_get_privatekey($privatekey, $this->privkeypass);
    }
    
    //publickey can be text or file path
    function set_publickey($publickey, $isFile=0){
        
        if ($isFile)$publickey=$this->readf($publickey);
        
        $this->publickey=openssl_get_publickey($publickey);
    }
    
    function set_ekey($ekey){
        $this->ekey=$ekey;
    }
    
    function set_privkeypass($pass){
        $this->privkeypass=$pass;
    }
    
    function set_plain($txt){
        $this->plaintext=$txt;
    }
    
    function set_crypttext($txt){
        $this->crypttext=$txt;
    }
    
    function encrypt($plain=""){
    
        if ($plain) $this->plaintext=$plain;
        
        openssl_seal($this->plaintext, $this->crypttext, $ekey, array($this->publickey));
        
        $this->ekey=$ekey[0];
    }
    
    function decrypt($crypt="", $ekey=""){
    
        if ($crypt)$this->crypttext=$crypt;
        if ($ekey)$this->ekey=$ekey;
        
        openssl_open($this->crypttext, $this->plaintext, $this->ekey, $this->privatekey);
    }
    
    function do_csr(
                    $countryName = "UK",
                    $stateOrProvinceName = "London",
                    $localityName = "Blah",
                    $organizationName = "Blah1",
                    $organizationalUnitName = "Blah2",
                    $commonName = "Joe Bloggs",
                    $emailAddress = "openssl@domain.com"
                    ){
        global $cfg;            
        $dn=Array(
                    "countryName" => $countryName,
                    "stateOrProvinceName" => $stateOrProvinceName,
                    "localityName" => $localityName,
                    "organizationName" => $organizationName,
                    "organizationalUnitName" => $organizationalUnitName,
                    "commonName" => $commonName,
                    "emailAddress" => $emailAddress
                    );
                    
        $privkey = openssl_pkey_new($this->config);
        if (!($privkey)) {
        	echo 'Failed to generate key pair.  Check '.$cfg['OPEN_SSL_CONF_PATH'].'.';
        	return;
        }
        
		$csr = openssl_csr_new($dn, $privkey, $this->config);
		if (!($csr)) {
        	echo 'Failed to generate csr.';
        	return;
        }
        
        $sscert = openssl_csr_sign($csr, null, $privkey, $cfg['OPEN_SSL_CERT_DAYS_VALID'], $this->config);
		openssl_x509_export($sscert, $this->publickey);
        openssl_pkey_export($privkey, $this->privatekey, $this->privkeypass, $this->config);
        openssl_csr_export($csr, $this->csr);
        
    }
    
    function get_plain(){
        return $this->plaintext;
    }
    
    function get_crypt(){
        return $this->crypttext;
    }
    
    function get_ekey(){
        return $this->ekey;
    }
    
    function get_privatekey(){
        return $this->privatekey;
    }
    
    function get_privkeypass(){
        return $this->privkeypass;
    }
    
    function get_publickey(){
        return $this->publickey;
    }

    function get_csr(){
        return $this->csr;
    }
}
}

// begin function definitions
if (!function_exists('ssl_save_identity')) {
function ssl_save_identity (
		    $siteid,	
                    $countryName = "CC",
                    $stateOrProvinceName = "XX",
                    $localityName = "City",
                    $organizationName = "Customer",
                    $organizationalUnitName = "Web Site",
                    $commonName = "www.example.com",
                    $emailAddress = ""
	) {
	$sep=',';

	$f1=fetch_certinfo($siteid);
	if ($f1) {
		$id=$f1['id'];
		$cmd="UPDATE certinfo SET ";
		$cmd .= "countryname=" . add_quotes($countryName) . $sep;
		$cmd .= "state=" . add_quotes($stateOrProvinceName) . $sep;
		$cmd .= "locality=" . add_quotes($localityName) . $sep;
		$cmd .= "orgname=" . add_quotes($organizationName) . $sep;
		$cmd .= "orgunit=" . add_quotes($organizationalUnitName) . $sep;
		$cmd .= "commonname=" . add_quotes($commonName) . $sep;
		$cmd .= "emailaddress=" . add_quotes($emailAddress);
	} else {

		$cmd="INSERT INTO certinfo (siteid,status,countryname,state,locality,orgname,orgunit,commonname,emailaddress) values (";
	
		$cmd .= add_quotes($siteid) . $sep;
		$cmd .= add_quotes(1) . $sep;
		$cmd .= add_quotes($countryName) . $sep;
		$cmd .= add_quotes($stateOrProvinceName) . $sep;
		$cmd .= add_quotes($localityName) . $sep;
		$cmd .= add_quotes($organizationName) . $sep;
		$cmd .= add_quotes($organizationalUnitName) . $sep;
		$cmd .= add_quotes($commonName) . $sep;
		$cmd .= add_quotes($emailAddress);
		$cmd .= ")";
	}
	mysql_query($cmd);
	
}
}

if (!function_exists('add_quotes')) {
function add_quotes ( $v ) {
	return "'" . $v . "'";
}
}

if (!function_exists('ssl_generate_csr')) {
function ssl_generate_csr($siteid,$cn) {

	$ossl = new OpenSSL;

	$cinfo = fetch_active_certinfo($siteid);

	if (!$cinfo) {
		return 2;
	}	

	$id=$cinfo['id'];
	$countryName=$cinfo['countryname'];
        $stateOrProvinceName=$cinfo['state'];
        $localityName=$cinfo['locality'];
        $organizationName=$cinfo['orgname'];
        $organizationalUnitName=$cinfo['orgunit'];
	if ($organizationalUnitName == '') {
		$organizationalUnitName=" ";
	}
        $commonName=$cn;
        $emailAddress=" ";

	$ossl->do_csr(
                    $countryName,
                    $stateOrProvinceName,
                    $localityName,
                    $organizationName,
                    $organizationalUnitName,
                    $commonName,
                    $emailAddress

	);
	
	$privatekey=$ossl->get_privatekey();

	$cmd="UPDATE certinfo set privatekey ='";
	$cmd .= $privatekey;
	$cmd .= "' WHERE id='" . $id . "'";
	$dbp=mysql_query($cmd);

	$csr=$ossl->get_csr();

	$cmd="UPDATE certinfo set csr ='";
	$cmd .= $csr;
	$cmd .= "' WHERE id='" . $id . "'";
	$dbp=mysql_query($cmd);

}
}

if (!function_exists('ssl_generate_temp_cert')) {
function ssl_generate_temp_cert($siteid,$cn) {

	$ossl = new OpenSSL;

	$cinfo = fetch_active_certinfo($siteid);

	if (! $cinfo) {
		return 2;
	}	
	$id=$cinfo['id'];
	$countryName=$cinfo['countryname'];
        $stateOrProvinceName=$cinfo['state'];
        $localityName=$cinfo['locality'];
        $organizationName=$cinfo['orgname'];
        $organizationalUnitName=$cinfo['orgunit'];
	if ($organizationalUnitName == '') {
		$organizationalUnitName=" ";
	}
        $commonName=$cn;
        $emailAddress=" ";
	
	$ossl->do_csr(
                    $countryName,
                    $stateOrProvinceName,
                    $localityName,
                    $organizationName,
                    $organizationalUnitName,
                    $commonName,
                    $emailAddress
	);


	$privatekey=$ossl->get_privatekey();

	$cmd="UPDATE certinfo set privatekey ='";
	$cmd .= $privatekey;
	$cmd .= "' WHERE id='" . $id . "'";
	$dbp=mysql_query($cmd);

	$csr=$ossl->get_csr();

	$cmd="UPDATE certinfo set csr ='";
	$cmd .= $csr;
	$cmd .= "' WHERE id='" . $id . "'";
	$dbp=mysql_query($cmd);

	$publickey=$ossl->get_publickey();

	$cmd="UPDATE certinfo set cert ='";
	$cmd .= $publickey;
	$cmd .= "' WHERE id='" . $id . "'";
	$dbp=mysql_query($cmd);


	update_certinfo($siteid);
}
}

if (!function_exists('ssl_set_cert')) {
function ssl_set_cert($siteid,$cn,$publickey) {

	$ossl = new OpenSSL;

	$cinfo = fetch_active_certinfo($siteid);

	if (! $cinfo) {
		return 2;
	}	
	$id=$cinfo['id'];

	$cmd="UPDATE certinfo set cert ='";
	$cmd .= $publickey;
	$cmd .= "' WHERE id='" . $id . "'";
	$dbp=mysql_query($cmd);


	update_certinfo($siteid);
}
}

if (!function_exists('fetch_certinfo')) {
function fetch_certinfo($key) {

	$cmd="SELECT * from certinfo where siteid='" . $key . "'";
	$dbp=mysql_query($cmd);
	if (! $dbp) {
		return false;	
	}
	if (mysql_num_rows($dbp) < 1) {
		return false;
	}

	return mysql_fetch_array($dbp);
}
}

if (!function_exists('fetch_active_certinfo')) {
function fetch_active_certinfo($key) {

	$cmd="SELECT id, siteid, status, countryname, state, locality, orgname, orgunit, commonname, emailaddress, privatekey, csr, cert, reserved1, hash FROM certinfo WHERE siteid='" . $key . "' AND status='1'";
	$dbp=mysql_query($cmd);
	if (!$dbp) {
		return false;
	}
	if (!mysql_num_rows($dbp)) {
		return false;
	}

	return mysql_fetch_array($dbp);
}
}

if (!function_exists('update_table_hash')) {
function update_table_hash ($table,$keyfield,$key,$hash) {
	global $cfg;
    // create md5 signature and insert it.
    $hash = crypt(md5(serialize($hash)), $cfg['key']);
	$cmd="UPDATE $table SET hash='$hash' WHERE $keyfield = '".$key."'";
    mysql_query($cmd);

}
}

if (!function_exists('update_certinfo')) {
function update_certinfo($key) {
    $hash = fetch_certinfo($key);
    $hash['hash'] = '';
	update_table_hash("certinfo","siteid",$key,$hash);
}
}

if (!function_exists('ssl_extract_privkey_file')) {
function ssl_extract_privkey_file($siteid,$filename) {
	global $restarthttp;
	$cinfo=fetch_certinfo($siteid);
	$current = file_get_contents($filename);
	if ($current != $cinfo['privatekey']) {
		write_string_to_file($filename,0640,$cinfo['privatekey']);
		$restarthttp = true;
	}
}
}

if (!function_exists('ssl_extract_cert_file')) {
function ssl_extract_cert_file($siteid,$filename) {
	$cinfo=fetch_certinfo($siteid);
	$current = file_get_contents($filename);
	if ($current != $cinfo['privatekey']) {
		write_string_to_file($filename,0640,$cinfo['cert']);
		$restarthttp = true;
	}
}
}

if (!function_exists('write_string_to_file')) {
function write_string_to_file ($filename,$mode=0644,$s) {
	$fp = fopen($filename,"w+");
        fwrite($fp,$s,20480);
        fclose($fp);
        // Set permissions
        chmod($filename,$mode);
}
}

if (!function_exists('msg_tag_display')) {
function msg_tag_display ($tag) {
	global $T;
	msg_display($T[$tag]);
}
}

if (!function_exists('ui_reload')) {
function ui_reload ($cp,$url,$number,$user) {
	$s="<script language='JavaScript1.3'>
<!-- 
load_url('./?cp=$cp&url=$url&number=$number&user=$user&confirm=".time()."')
// -->
</script>";

	echo $s;
}
}

if (!function_exists('msg_display')) {
function msg_display ($msg) {
	$s="<br><div align='center'><b>" . $msg . "</b></div><br>\n";
	echo $s;
}
}
// end of module

?> 
